package com.itqf.dao.impl;

import com.itqf.dao.CartDao;
import com.itqf.pojo.Cart;
import com.itqf.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * projectName: gpshop
 *
 * @author: 赵伟风
 * time: 2021/7/22 20:36
 * description:
 */
public class CartDaoImpl implements CartDao {

    /**
     * 检查购物车是否存在
     *
     * @param uId
     * @param gId
     * @return
     */
    @Override
    public Cart check(int uId, String gId) throws SQLException {
        String sql = "select c_id cId ,u_id uId , g_id gId , c_number cNumber ," +
                                    " c_total cTotal from cart where u_id = ? and g_id = ? ;";
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        Cart cart = queryRunner.query(sql, new BeanHandler<>(Cart.class), uId, gId);
        return cart;
    }
    /**
     * 修改购物车数量和小计
     *
     * @param cart
     */
    @Override
    public void updateCart(Cart cart) throws SQLException {
        String sql = "update cart set c_number = ? ,c_total = ? where c_id = ?;";
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        queryRunner.update(sql, cart.getcNumber(),cart.getcTotal(),cart.getcId());
    }
    /**
     * 添加购物车数据
     * @param cart
     */
    @Override
    public void insertCart(Cart cart) throws SQLException {

        String sql = "insert into cart (u_id,g_id,c_number,c_total) value (?,?,?,?);";
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        queryRunner.update(sql,cart.getuId(),cart.getgId(),cart.getcNumber(),cart.getcTotal());
    }

    /**
     * 数据库多表查询!
     *
     * @param uId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryAll(int uId) throws SQLException {

        String sql = " SELECT c.c_id cId,c.u_id uId,c.g_id gId,c.c_number cNumber," +
                "        c.c_total cTotal, g.c_id tId,g.g_name gName,g.g_price gPrice," +
                "        g.g_img gImg,g.g_date gDate,g.g_rank gRank , g.g_detail gDetail " +
                "        FROM cart c LEFT JOIN goods g ON c.g_id = g.g_id " +
                "        WHERE c.u_id = ?";

        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

        List<Map<String, Object>> mapList = queryRunner.query(sql, new MapListHandler(), uId);

        return mapList;
    }
}
